package com.speed.aop;

import java.lang.reflect.Method;
import java.util.UUID;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * LogAOP
 * 
 * @date 2016年8月5日 下午1:42:09
 * @author wangjwm
 *
 */
@Aspect
@Component
public class LogAop {

	ThreadLocal<Long> time = new ThreadLocal<Long>();
	ThreadLocal<String> tag = new ThreadLocal<String>();

	/**
	 * 在所有标注@Log的地方切入
	 * 
	 * @param joinPoint
	 */
	@Before("@annotation(com.speed.aop.ControllerLog)")
	public void beforeExec(JoinPoint joinPoint) {

		time.set(System.currentTimeMillis());
		tag.set(UUID.randomUUID().toString());

		info(joinPoint);

		MethodSignature ms = (MethodSignature) joinPoint.getSignature();
		Method method = ms.getMethod();
		String msg = method.getAnnotation(ControllerLog.class).remark() + "标记" + tag.get();
		LogUtil.aopLog(msg);
	}

	@After("@annotation(com.speed.aop.ControllerLog)")
	public void afterExec(JoinPoint joinPoint) {
		MethodSignature ms = (MethodSignature) joinPoint.getSignature();
		Method method = ms.getMethod();
		String msg = "标记为\"" + method.getAnnotation(ControllerLog.class).remark() + "\"的方法" + method.getName() + "运行消耗" + (System.currentTimeMillis() - time.get()) + "ms";
		LogUtil.aopLog(msg);
	}

	private void info(JoinPoint joinPoint) {
		LogUtil.aopLog("--------------------------------------------------");
		LogUtil.aopLog("Kind:\t" + joinPoint.getKind()+"	StaticPart:\t" + joinPoint.getStaticPart());
		Object[] os = joinPoint.getArgs();
		StringBuffer sb = new StringBuffer();
		sb.append("Args:");
		for (int i = 0; i < os.length; i++) {
			sb.append("\t==>参数[" + i + "]:\t" + os[i].toString());
		}
		LogUtil.aopLog(sb.toString());

		LogUtil.aopLog("SourceLocation:\t" + joinPoint.getSourceLocation());
		LogUtil.aopLog("--------------------------------------------------");
	}

}
